package com.stars.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stars.base.constants.CommonNumberConstants;
import com.stars.base.constants.RedisConstants;
import com.stars.base.constants.SeparatorConstants;
import com.stars.base.entity.SessionUser;
import com.stars.module.setting.entity.SystemSetting;
import com.stars.module.setting.mapper.SystemSettingMapper;
import com.stars.util.cache.CacheUtil;
import com.stars.util.common.DevelopKit;
import com.stars.util.context.SpringContextUtil;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
@DependsOn({"springContextUtil"})
public class DBConfig {
    private static final CacheUtil cacheUtil;
    private static final SystemSettingMapper settingMapper;

    static {
        cacheUtil = SpringContextUtil.getBean(CacheUtil.class);
        settingMapper = SpringContextUtil.getBean(SystemSettingMapper.class);
    }

    public static void initSystemConfig() {
        initConfig("1");
    }

    /**
     * @author : mango
     * @date : 2023/3/17 16:38
     * @param configType:配置级别（预留）
     * @description :初始化配置
     */
    public static void initConfig(String configType) {
        LambdaQueryWrapper<SystemSetting> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(SystemSetting::getType, configType);

        List<SystemSetting> listDefine = settingMapper.selectList(wrapper);

        boolean prefix;
        String key;
        if (CommonNumberConstants.ONE_STR.equals(configType)) {
            prefix = false;
            key = RedisConstants.SETTING_PREFIX;
        } else if (CommonNumberConstants.TWO_STR.equals(configType)) {
            prefix = true;
            key = RedisConstants.SETTING_PREFIX;
        } else {
            prefix = false;
            assert DevelopKit.getSessionUser()!=null;
            key = RedisConstants.SETTING_PREFIX+DevelopKit.getSessionUser().getUserId()+ SeparatorConstants.COLON;
        }

        if(listDefine!=null && !listDefine.isEmpty()){
            listDefine.forEach((item)-> cacheUtil.setValue(prefix,key+item.getSystemId(),item.getConfigValue()));
        }
    }

    /**
     * 获取设置
     * @author : Rocks
     * @date :  2023/11/23 22:09
     * @param key 设置的key
     * @param user 当前用户
     * @return String
     */
    public static String getString(String key, SessionUser user) {

        String unitId,userId;

        if (user != null) {
            unitId = user.getCurrentUnit();
            userId = user.getUserId();
        } else {
            userId = "user";
            unitId = "unit";
        }

        String result = (String) cacheUtil.getValue(false, RedisConstants.SETTING_PREFIX + key);

        if (StringUtils.hasLength(result)) {
            return result;
        }

        result = (String) cacheUtil.getValue(false, RedisConstants.UNIT_SETTING_PREFIX + unitId + SeparatorConstants.COLON + key);

        if (StringUtils.hasLength(result)) {
            return result;
        }

        LambdaQueryWrapper<SystemSetting> wrapper = new LambdaQueryWrapper<>();

        wrapper.and(query -> query.eq(SystemSetting::getSystemId,key).eq(SystemSetting::getType, CommonNumberConstants.ONE_STR))
                .or(query -> query.eq(SystemSetting::getSystemId,key).eq(SystemSetting::getType, CommonNumberConstants.TWO_STR).eq(SystemSetting::getCreateUnitId,unitId))
                .or(query -> query.eq(SystemSetting::getSystemId,key).eq(SystemSetting::getType, CommonNumberConstants.THREE_STR).eq(SystemSetting::getCreateUserId,userId));

        SystemSetting setting = settingMapper.selectOne(wrapper);

        if (null == setting) {
            return "";
        }

        if (CommonNumberConstants.ONE_STR.equals(setting.getType())) {
            cacheUtil.setValue(false, RedisConstants.SETTING_PREFIX + key, setting.getConfigValue());
        } else if (CommonNumberConstants.TWO_STR.equals(setting.getType())) {
            cacheUtil.setValue(false, RedisConstants.UNIT_SETTING_PREFIX + unitId + SeparatorConstants.COLON + key, setting.getConfigValue());
        } else {
            cacheUtil.setValue(false, RedisConstants.USER_SETTING_PREFIX + userId + SeparatorConstants.COLON + key, setting.getConfigValue());
        }

        return setting.getConfigValue();
    }

}
